Tuples

Tuple is a collection of Python objects much like a list. The sequence of values stored in a tuple can be of any type, and they are indexed by integers.Tuples are immutable lists and cannot be changed in any way once it is created.

Some of the characteristics features of Tuples are:
  • Tuples are defined in the same way as lists.
  • They are enclosed within parenthesis and not within square braces.
  • Elements of the tuple must have a defined order.
  • Negative indices are counted from the end of the tuple, just like lists.
  • Tuple also has the same structure where commas separate the values.
Creating tuples in Python
An example showing how to build tuples in Python:
tupl1 = ('computersc', 'IT', 'CSE');
tup2 = (6,5,4,3,2,1);

An empty Tuple
t=()
print(" An empty Tuple")
print(t)

Tuple with Strings
t=("Python","is","programing","language")
print("tuple with String")
print(t)

Tuple with List
list=[1,2,3,4,5]
print("tuple using List")
print(tuple(list))

Creating tuple with building Function
t=tuple('Python')
 

Accessing the elements of tuples
tupl1 = ('computersc', 'IT', 'CSE');
tupl2 = (1993, 2016);
tupl3 = (2, 4, 6, 8, 10, 12, 14, 16);

print ("tupl1[0]", tupl1[0])
print ("tupl3[2:4]", tupl3[2:4])

Updating Tuples
They are immutable, i.e., the values can't be changed directly. So we can just update by joining tuples. Let's demonstrate this with an example:

tupl1 = (2, 3, 4);
tupl2 = ('ab', 'cd');
tupl3 = tupl1 + tupl2
print (tupl3)

Deleting the elements of tuples
del tuple_name;
tupl3 = (2, 4, 6, 8, 10, 12, 14, 16);
del tupl3

What are lists and tuples? What is the key difference between the two?
Lists and Tuples are both sequence data types that can store a collection of objects in Python. The objects stored in both sequences can have different data types. Lists are represented with square brackets ['sara', 6, 0.19], while tuples are represented with parantheses ('ansh', 5, 0.97). But what is the real difference between the two? The key difference between the two is that while lists are mutable, tuples on the other hand are immutable objects. This means that lists can be modified, appended or sliced on the go but tuples remain constant and cannot be modified in any manner.

No comments:

Post a Comment